package com.xuexie.mr;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class RunWeather {

	public static Text k=new Text();
	public static IntWritable v=new IntWritable(1);
	
	public static void main(String[] args) {
		Configuration config =new Configuration();
//		config.set("fs.defaultFS", "hdfs://node2:8020");
//		config.set("yarn.resourcemanager.hostname", "node3");
		config.set("mapred.jar", "C:\\Users\\Administrator\\Desktop\\weather.jar");
		try {
			FileSystem fs =FileSystem.get(config);
			Job job =Job.getInstance(config);
			job.setJarByClass(RunWeather.class);
			
			job.setJobName("weather.jar");
			
			job.setMapperClass(WeatherMapper.class);
			job.setReducerClass(WeatherReducer.class);
			
			job.setPartitionerClass(MyPartitioner.class);
			job.setSortComparatorClass(MySort.class);
			job.setGroupingComparatorClass(MyGroup.class);
			
			job.setNumReduceTasks(3);
			job.setMapOutputKeyClass(MyBean.class);
			job.setMapOutputValueClass(Text.class);
			
			//设置MR执行的输入文件
			FileInputFormat.setInputPaths(job, new Path("/usr/input/weather"));
			
			//该目录表示MR执行之后的结果数据所在目录，必须不能存在
			Path outputPath=new Path("/usr/output/weather");
			if(fs.exists(outputPath)){
				fs.delete(outputPath, true);
			}
			FileOutputFormat.setOutputPath(job, outputPath);
			
			boolean f =job.waitForCompletion(true);
			if(f){
				System.out.println("job 成功执行");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}

	static class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
		//map task执行过程中调用的方法，计算框架会循环调用该方法，默认每行数据调用一次
		protected void map(LongWritable key, Text value,
				Context context)
				throws IOException, InterruptedException {
			String line=value.toString();
			StringTokenizer st =new StringTokenizer(line);
			while( st.hasMoreTokens()){
				String word =st.nextToken();
				k.set(word);
				context.write(k, v);
			}
		}
	}
	
	static class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
		protected void reduce(Text arg0, Iterable<IntWritable> arg1,
				Context arg2)
				throws IOException, InterruptedException {
			int sum=0;
			for(IntWritable i:arg1){
				sum=sum+i.get();
			}
			v.set(sum);
			arg2.write(arg0, v);
		}
	}
}
